#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/8/16 10:22
# @Author  : youfeng
import random
import threading
import time

from config import LOCK_REDIS_CONF
from dao.proxy_lock_dao import ProxyLockDAO
from entity.proxy_entity import ProxyEntity
from entity.request_entity import RequestEntity


class ProxyService(threading.Thread):
    def __init__(self, log):
        super(ProxyService, self).__init__()
        self.log = log

        # 管理请求
        self.__request_dict_manage = {}

        # 初始化代理加载接口
        self.__proxy_dao = ProxyLockDAO(LOCK_REDIS_CONF, self.log)

        # 代理管理
        self.__proxy_dict_manage = self.__get_proxy_dict()

        # 启动线程
        self.start()

        # 加载代理
        self.log.info("代理接口初始化完成...")

    # 获取代理接口
    def get_proxy(self, host, tag):
        proxy_manage = self.__proxy_dict_manage.get(tag)
        if proxy_manage is None:
            return None

        if host is None:
            return None

        request_manage = self.__request_dict_manage.get(host)
        if request_manage is None:
            request_manage = RequestEntity(host)
            self.__request_dict_manage[host] = request_manage

        # 获得当前遍历指针
        current_point = request_manage.get_request_point(tag)

        # 获得代理，以及代理的位置
        proxy, index = proxy_manage.get_proxy(current_point)
        if proxy is None:
            return None

        # 保存遍历指针
        request_manage.set_request_point(tag, index + 1)
        return proxy

    # 获得所有代理
    def __get_proxy_dict(self):
        proxy_dict_manage = {}
        proxy_list_dict = self.__proxy_dao.get_proxy()
        for tag, proxy_list in proxy_list_dict.iteritems():
            proxy_manage = ProxyEntity(tag, proxy_list)
            proxy_dict_manage[tag] = proxy_manage
            self.log.info("当前获取代理: tag = {} num = {}".format(proxy_manage.get_tag(), proxy_manage.get_length()))
        return proxy_dict_manage

    # 运行线程
    def run(self):
        while True:
            # 获取代理
            proxy_dict_manage = self.__get_proxy_dict()
            self.__proxy_dict_manage = proxy_dict_manage

            # 休眠一段时间
            time.sleep(random.randint(4, 7))
